<template>
  <div>
    <!-- <el-card shadow="always" :body-style="{ padding: '20px' }"> -->
    <!-- 搜索栏 -->
    <div class="search-bar">
      <el-input clearable v-model="query.questionText" placeholder="请输入题目关键字" />
      <el-select v-if="path !== '/dataanalysis'" clearable v-model="query.typeCode" placeholder="题目类型"
        style="margin-left: 10px; width: 200px">
        <el-option v-for="item in typeOptions" :key="item.value" :label="item.label" :value="item.value" />
      </el-select>
      <el-button type="primary" @click="loadQuestions" style="margin-left: 10px"> 查询 </el-button>
      <el-button type="success" @click="handleAdd" style="margin-left: 10px"> 新增题目 </el-button>
    </div>

    <!-- 题目列表 -->
    <el-table border :header-cell-style="{ background: '#f5f7fa' }" :data="questionList"
      style="width: 100%; margin-top: 20px" height="calc(100vh - 300px)" @expand-change="handleExpand"
      @row-click="handleRowClick">
      <el-table-column type="expand">
        <template #default="{ row }">
          <div class="expand-detail">
            <div class="detail-section">
              <div class="detail-label">题目类型：</div>
              <div class="detail-content">
                {{typeOptions.find(t => t.value === row.typeCode)?.label}}
                <span v-if="row.typeCodeChildren">->
                  {{typeOptions.find(t => t.value === row.typeCode)?.children?.
                    find(t => t.value === row.typeCodeChildren)?.label}}
                </span>
              </div>
            </div>
            <div class="detail-section">
              <div class="detail-label">来源：</div>
              <div class="detail-content">{{ row.source || '暂无来源' }}</div>
            </div>
            <div class="detail-section">
              <div class="detail-label">选项：</div>
              <div class="detail-content options-content">
                <div v-for="option in row.options" :key="option.optionLabel" class="option-item-expand">
                  <div class="option-label-expand">
                    <span v-if="row.questionType == 1 || row.questionType == 2"> {{ option.optionLabel }}.</span>
                    <span v-else-if="row.questionType == 99">
                      <span v-if="option.optionLabel == 'A'">
                        <el-icon :size="20">
                          <circle-check />
                        </el-icon>
                      </span>
                      <span v-else-if="option.optionLabel == 'B'">
                        <el-icon :size="20">
                          <circle-close />
                        </el-icon>
                      </span>
                    </span>
                    <span v-else> {{ option.optionLabel }}.</span>
                  </div>
                  <div class="option-text" v-html="option.optionText"></div>
                  <div v-if="option.isCorrect" class="correct-tag">正确答案</div>
                </div>
              </div>
            </div>
            <div class="detail-section">
              <div class="detail-label">解析：</div>
              <div class="detail-content" v-html="row.analysis || '暂无解析'"></div>
            </div>
          </div>
        </template>
      </el-table-column>
      <el-table-column v-if="path !== '/dataanalysis'" prop="orders" sortable label="#" width="100" align="center" />
      <el-table-column prop="questionText" label="题目内容" min-width="100">
        <template #default="{ row }">
          <div class="question-text">
            <div v-html="row.questionText"></div>
          </div>
        </template>
      </el-table-column>
      <el-table-column prop="typeCode" label="题目类型" width="120" align="center">
        <template #default="{ row }">
          {{ getTypeLabel(row.typeCode) }}
          <span v-if="row.typeCodeChildren">->
            {{typeOptions.find(t => t.value === row.typeCode)?.children?.
              find(t => t.value === row.typeCodeChildren)?.label}}
          </span>
        </template>
      </el-table-column>
      <!-- 来源 -->
      <!-- <el-table-column prop="source" label="来源" width="120" align="center" /> -->
      <el-table-column label="操作" align="center" fixed="right" width="200">
        <template #default="{ row }">
          <el-button type="primary" size="small" @click="handleView(row)">
            <el-icon>
              <View />
            </el-icon>
          </el-button>
          <el-button type="primary" size="small" @click="handleEdit(row)">
            <el-icon>
              <Edit />
            </el-icon>
          </el-button>
          <el-button type="danger" size="small" @click="handleDelete(row)">
            <el-icon>
              <Delete />
            </el-icon>
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <el-pagination v-model:current-page="query.pageNum" v-model:page-size="query.pageSize" :total="total"
      @current-change="loadQuestions" @size-change="loadQuestions" layout="->,total,  prev, pager, next"
      style="margin-top: 20px" />

    <!-- 新增/编辑对话框 -->
    <el-drawer v-model="dialogVisible" :title="dialogType === 'add' ? '新增题目' : '编辑题目'" direction="rtl" size="60%"
      custom-class="timudraw">
      <div class="drawer-container">
        <el-form :model="questionForm" :rules="rules" ref="formRef" label-width="100px" class="drawer-form">
          <el-form-item label="题目分类" prop="questionType">
            <!-- 是否是判断题 -->
            <el-checkbox @change="questionTypeChange" false-label="" true-label="99" v-model="questionForm.questionType"
              label="1">判断题</el-checkbox>
          </el-form-item>
          <el-form-item label="题目类型" prop="typeCode">
            <el-radio-group v-model="questionForm.typeCode" class="radio-group-type">
              <el-radio v-for="item in typeOptions" :key="item.value" :label="item.value" border>
                {{ item.label }}
              </el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="子类型" prop="typeCodeChildren" v-if="typeChildrenList.length">
            <el-radio-group v-model="questionForm.typeCodeChildren" class="radio-group-type">
              <el-radio v-for="item in typeChildrenList" :key="item.value" :label="item.value" border>
                {{ item.label }}
              </el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item v-if="path !== '/dataanalysis'" label="题目顺序" prop="orders">
            <el-input v-model="questionForm.orders" type="number" />
          </el-form-item>
          <el-form-item label="题干" prop="questionText">
            <wang v-if="questionForm.questionText" height="200px" v-model="questionForm.questionText" />
          </el-form-item>
          <el-form-item label="一键填充模式" prop="" v-if="questionForm.questionType != 99">
            <el-button type="primary" size="default" @click="quicklyModel">一键填充答案</el-button>
          </el-form-item>
          <el-form-item label="选项" prop="options">
            <div class="options-list">
              <div v-for="(option, index) in questionForm.options" :key="index" class="option-row">
                <span class="option-label">{{ option.optionLabel }}.</span>
                <div class="option-editor">
                  <wang v-model="option.optionText" height="100px" />
                </div>
                <!-- <el-radio v-model="correctAnswer" :label="option.optionLabel" @change="handleCorrectChange">
                  正确答案
                </el-radio> -->
                <el-checkbox v-model="correctAnswer" :disabled="questionForm.questionType == 99"
                  :label="option.optionLabel" @change="handleCorrectChange">
                  正确答案
                </el-checkbox>
              </div>
            </div>
          </el-form-item>
          <el-form-item label="题目解析" prop="analysis">
            <wang mode="simple" height="200px" v-model="questionForm.analysis" />
          </el-form-item>
          <el-form-item label="知识点" prop="knowledge">
            <el-input v-model="questionForm.knowledge" placeholder="请输入知识点" />
          </el-form-item>
        </el-form>
      </div>
      <template #footer>
        <div style="flex: auto">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmit">确定</el-button>
        </div>
      </template>
    </el-drawer>

    <!-- 添加查看详情对话框 -->
    <el-dialog v-model="viewDialogVisible" top="2%" title="题目详情" width="60%">
      <div class="question-detail">
        <div class="detail-item">
          <label>题目内容：</label>
          <div v-html="viewForm.questionText"></div>
        </div>
        <div class="detail-item">
          <label>题目类型：</label>
          <div>{{typeOptions.find(t => t.value === viewForm.typeCode)?.label}}
            <span v-if="viewForm.typeCodeChildren">->
              {{typeOptions.find(t => t.value === viewForm.typeCode)?.children?.
                find(t => t.value === viewForm.typeCodeChildren)?.label}}
            </span>

          </div>
        </div>
        <div class="detail-item">
          <label>来源：</label>
          <div>{{ viewForm.source || '暂无来源' }}</div>
        </div>
        <div class="detail-item">
          <label>选项：</label>
          <div style="display: flex" v-for="option in viewForm.options" :key="option.optionLabel" class="option-item">
            <div style="width: 30px">
              <!-- {{ option.optionLabel }}. -->
              <span v-if="viewForm.questionType == 1 || viewForm.questionType == 2"> {{ option.optionLabel }}.</span>
              <span v-else>
                <span v-if="option.optionLabel == 'A'">
                  <el-icon :size="20">
                    <circle-check />
                  </el-icon>
                </span>
                <span v-else-if="option.optionLabel == 'B'">
                  <el-icon :size="20">
                    <circle-close />
                  </el-icon>
                </span>
              </span>
            </div>
            <span v-html="option.optionText"></span>
            <span v-if="option.isCorrect" class="correct-answer">（正确答案）</span>
          </div>
        </div>
        <div class="detail-item">
          <label>解析：</label>
          <div v-html="viewForm.analysis || '暂无解析'"></div>
        </div>
      </div>
    </el-dialog>
    <!-- </el-card> -->
  </div>
</template>

<script setup lang="ts">
import { findAll, delquestion, addquestion } from '../api/timu';
import { ref, onMounted, watch } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { typeOptionsList, getTypeLabel, getType } from '../utils/type';
// import wang from '../../../plugins/editor-wang/components/wang.vue';
import { Edit, Delete, View } from '@element-plus/icons-vue';

import { findByDataId } from '../api/dataAnalysis';
import { useRouter, useRoute } from 'vue-router';
import { maxOrder } from '../api/index';
const path = ref('');

const props = defineProps({
  shijuanId: {
    type: String
  },
  materialId: {
    type: String
  }
});

const query = ref({
  pageNum: 1,
  pageSize: 1000,
  questionText: '',
  typeCode: '',
  paperId: props.shijuanId
});

const typeOptions = ref(typeOptionsList);

const questionList = ref<any>([]);
const total = ref(0);
const dialogVisible = ref(false);
const dialogType = ref('add');
// const correctAnswer = ref('');
const correctAnswer = ref<any>([]);
const typeChildrenList = ref<any>([])

const questionForm: any = ref({
  orders: '',
  questionText: '',
  typeCode: '',
  options: [
    { optionText: '', isCorrect: false, optionLabel: 'A' },
    { optionText: '', isCorrect: false, optionLabel: 'B' },
    { optionText: '', isCorrect: false, optionLabel: 'C' },
    { optionText: '', isCorrect: false, optionLabel: 'D' }
  ],
  analysis: '',
  knowledge: '',
  questionType: ''
});
// 题目分类改变
const questionTypeChange = (e) => {
  if (questionForm.value.questionType == 99) {
    questionForm.value.options = [
      { optionText: '正确', isCorrect: true, optionLabel: 'A' },
      { optionText: '错误', isCorrect: false, optionLabel: 'B' },
    ]
    correctAnswer.value.push('A')
  } else {
    questionForm.value.options = [
      { optionText: '', isCorrect: false, optionLabel: 'A' },
      { optionText: '', isCorrect: false, optionLabel: 'B' },
      { optionText: '', isCorrect: false, optionLabel: 'C' },
      { optionText: '', isCorrect: false, optionLabel: 'D' }
    ]
    correctAnswer.value = []
  }
  console.log(questionForm.value.options)
}
const formRef = ref<any>(null);

const rules = {
  orders: [{ required: true, message: '请输入题目顺序', trigger: 'blur' }],
  questionText: [
    { required: true, message: '请输入题目内容', trigger: 'blur' },
    { min: 2, message: '  目内容至少2个字符', trigger: 'blur' }
  ],
  typeCode: [{ required: true, message: '请选择题目类型', trigger: 'change' }],
  options: [
    {
      validator: (rule, value, callback) => {
        // 检查所有选项是否都填写了内容
        const emptyOption = value.find(opt => !opt.optionText.trim());
        if (emptyOption) {
          callback(new Error('请填写所有选项内容'));
          return;
        }
        // 检查是否选择了正确答案
        const hasCorrect = value.some(opt => opt.isCorrect);
        if (!hasCorrect) {
          // callback(new Error('请选择正确答案'));
          callback(new Error('请至少选择一个正确答案'));

          return;
        }
        callback();
      },
      trigger: 'change'
    }
  ],
  knowledge: [{ required: true, message: '请输入知识点', trigger: 'blur' }]
};

const loadQuestions = async () => {
  // 当前路由
  if (path.value.includes('/dataanalysis')) {
    try {
      const res = await findByDataId({
        id: props.materialId
      });
      questionList.value = res.data.records;
      total.value = res.data.total;
    } catch (error) {
      ElMessage.error('加载题目失败');
    }
  } else {
    if (props.materialId) {
      try {
        const res = await findByDataId({
          id: props.materialId,
          paperId: props.shijuanId
        });
        questionList.value = res.data.records;
        total.value = res.data.total;
      } catch (error) {
        ElMessage.error('加载题目失败');
      }
    } else {
      try {
        const res = await findAll(query.value);
        questionList.value = res.data.records.filter(q => q.typeCode != 'data');
        total.value = res.data.total;
      } catch (error) {
        ElMessage.error('加载题目失败');
      }
    }
  }
  questionList.value.forEach(item => {
    if (item.typeCode && item.typeCode != 'data' && item.typeCode.length > 1) {
      item.typeCodeChildren = item.typeCode
      item.typeCode = item.typeCode.slice(0, 1)
    }
  })
  getMaxOrder();
};
const scrollTop = () => {
  setTimeout(() => {
    const body = document.querySelectorAll('.el-drawer__body');
    // 取第二个
    let two = body[1];
    console.log(two);
    try {
      two.scrollTop = 0;
    } catch (error) {
      console.log(error);
    }
  }, 400);
};
const handleAdd = () => {
  dialogType.value = 'add';
  questionForm.value = {
    questionText: '',
    typeCode: '',
    typeCodeChildren: '',
    options: [
      { optionText: '', isCorrect: false, optionLabel: 'A' },
      { optionText: '', isCorrect: false, optionLabel: 'B' },
      { optionText: '', isCorrect: false, optionLabel: 'C' },
      { optionText: '', isCorrect: false, optionLabel: 'D' }
    ],
    analysis: '',
    knowledge: '',
    questionType: ''
  };
  if (props.materialId) {
    questionForm.value.typeCode = 'a';
  }
  typeChildrenList.value = []
  correctAnswer.value = [];
  dialogVisible.value = true;
  if (formRef.value) {
    formRef.value.resetFields();
  }
  getMaxOrder();
};

const handleEdit = row => {
  dialogType.value = 'edit';
  questionForm.value = {}
  questionForm.value = JSON.parse(JSON.stringify(row));
  console.log(questionForm.value);
  if (questionForm.value.options) {
    // correctAnswer.value =
    //   questionForm.value.options.find(opt => opt.isCorrect)?.optionLabel || '';
    correctAnswer.value = questionForm.value.options
      .filter(opt => opt.isCorrect)
      .map(opt => opt.optionLabel);
  }
  setTimeout(() => {
    dialogVisible.value = true;
  }, 300);
  if (formRef.value) {
    formRef.value.resetFields();
  }
};

const handleDelete = row => {
  ElMessageBox.confirm('确认删除该题目吗？', '提示', {
    type: 'warning'
  }).then(async () => {
    try {
      await delquestion(row.id);
      ElMessage.success('删除成功');
      loadQuestions();
    } catch (error) {
      ElMessage.error('删除失败');
    }
  }).catch(() => {
  });
};

const handleCorrectChange = () => {
  questionForm.value.options.forEach(option => {
    // option.isCorrect = option.optionLabel === correctAnswer.value;

    option.isCorrect = correctAnswer.value.includes(option.optionLabel);

  });
};
const quicklyModel = () => {
  console.log(questionForm.value.options);
  let optionArr = ['A', 'B', 'C', 'D']
  questionForm.value.options.forEach((option, index) => {
    option.optionText = optionArr[index]
  });
};

const emit = defineEmits(['refresh', 'scrollToQuestion']);

const handleSubmit = async () => {
  if (!formRef.value) return;
  if (questionForm.value.typeCodeChildren) {
    questionForm.value.typeCode = questionForm.value.typeCodeChildren
  }
  try {
    await formRef.value.validate();
    if (path.value.includes('/dataanalysis')) {
      questionForm.value.dataId = props.materialId;
      //删除orders
      delete questionForm.value.orders;
    } else {
      questionForm.value.paperId = props.shijuanId;
      if (props.materialId) {
        questionForm.value.dataId = props.materialId;
      }
    }
    const res: any = await addquestion(questionForm.value);
    if (res.code === 200) {
      // handleAdd();

      // 发射事件，新增题目才是发射事件
      if (dialogType.value == 'add') {
        ElMessage.success('添加成功');
        dialogVisible.value = false;
        loadQuestions();
        emit('refresh');
      } else {
        ElMessage.success('更新成功');
        dialogVisible.value = false;
        loadQuestions();
      }
    } else {
      ElMessage.error(res.msg);
    }

    loadQuestions();
  } catch (error: any) {
    if (error.message) {
      ElMessage.error(error.message);
    } else {
      ElMessage.error(dialogType.value === 'add' ? '添加失败' : '更新失败');
    }
  }
};

const viewDialogVisible = ref(false);
const viewForm = ref<any>({
  questionText: '',
  typeCode: '',
  options: [],
  analysis: ''
});

const handleView = row => {
  viewForm.value = JSON.parse(JSON.stringify(row));
  viewDialogVisible.value = true;
};

const handleExpand = (row, expandedRows) => {
  console.log('expanded', row, expandedRows);
};

const handleRowClick = row => {
  emit('scrollToQuestion', row.orders);
};

onMounted(() => {
  const route = useRoute();
  path.value = route.path;
  if (props.materialId) {
    let typearr = ['c', 'b', 'd', 'x', 'e1', 'e2', 'e3'];
    typeOptions.value = typeOptionsList.filter(item => !typearr.includes(item.value));
  }
  loadQuestions();
});
defineExpose({
  loadQuestions
});

const getMaxOrder = async () => {

  if (dialogType.value != 'edit') {
    try {
      const res = await maxOrder(props.shijuanId);
      console.log(res.data);
      questionForm.value.orders = res.data;
      scrollTop();
    } catch (err) {
      console.log(err);
    }
  }

};

// 题目类型改变

const handleTypeChange = (val) => {
  const typeList: any = getType(val)
  typeChildrenList.value = []
  console.log(typeList)
  if (typeList?.children) {
    typeChildrenList.value = typeList.children
    if (!questionForm.value.typeCodeChildren) {
      if (questionForm.value.typeCode == 'b') {
        questionForm.value.typeCodeChildren = 'b2'
      } else if (questionForm.value.typeCode == 'f') {
        questionForm.value.typeCodeChildren = 'f2'
      } else if (questionForm.value.typeCode == 'a') {
        questionForm.value.typeCodeChildren = 'a3'
      }

    } else {
      // let first = [...questionForm.value.typeCodeChildren][0]
      // if (first != questionForm.value.typeCode) {
      //   if (questionForm.value.typeCode == 'b') {
      //     questionForm.value.typeCodeChildren = 'b2'
      //   } else if (questionForm.value.typeCode == 'f') {
      //     questionForm.value.typeCodeChildren = 'f2'
      //   } else if (questionForm.value.typeCode == 'a') {
      //     questionForm.value.typeCodeChildren = 'a3'
      //   }
      // }
    }
  }
}

watch(() => questionForm.value.typeCode, (val) => {
  if (val) {
    handleTypeChange(val)
  }
}, { immediate: true, deep: true })
</script>

<style lang="scss" scoped>
.search-bar {
  display: flex;
  align-items: center;
  margin-bottom: 20px;
}

.options-list {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.option-row {
  display: flex;
  align-items: flex-start;
  margin-bottom: 20px;

  .option-label {
    width: 30px;
    margin-right: 10px;
    padding-top: 8px;
  }

  .el-radio {
    margin-left: 20px;
    padding-top: 8px;
  }
}

.question-text {
  max-height: 100px;
  overflow-y: auto;
  line-height: 1.8;
  padding: 12px 16px;
  background-color: #f8f9fa;
  border-radius: 4px;
  border-left: 4px solid #409eff;

  // 调整滚动条样式
  &::-webkit-scrollbar {
    width: 6px;
  }

  &::-webkit-scrollbar-thumb {
    background-color: #ddd;
    border-radius: 3px;
  }

  &::-webkit-scrollbar-track {
    background-color: #f5f5f5;
  }

  // 调整题目内容样式
  ::v-deep(p) {
    margin: 0;
    color: #303133;
  }

  ::v-deep(img) {
    max-width: 100%;
    height: auto;
    margin: 8px 0;
  }
}

.question-detail {
  padding: 20px;

  .detail-item {
    margin-bottom: 24px;

    label {
      font-weight: bold;
      margin-bottom: 12px;
      display: block;
      color: #606266;
    }

    div {
      line-height: 1.6;
      color: #303133;
    }
  }

  .option-item {
    margin: 12px 0;
    padding: 8px 12px;
    background-color: #f8f9fa;
    border-radius: 4px;

    .correct-answer {
      color: #67c23a;
      margin-left: 12px;
      font-weight: 500;
    }
  }
}

.option-editor {
  flex: 1;
  margin-right: 20px;
  max-width: 700px;
}

.expand-detail {
  padding: 20px 50px;
  background-color: #deedfb;

  .detail-section {
    display: flex;
    margin-bottom: 20px;

    &:last-child {
      margin-bottom: 0;
    }

    .detail-label {
      width: 80px;
      color: #606266;
      font-weight: 500;
    }

    .detail-content {
      flex: 1;
      color: #303133;

      &.options-content {
        display: flex;
        flex-direction: column;
        gap: 12px;
      }
    }
  }
}

.option-item-expand {
  display: flex;
  align-items: flex-start;
  padding: 8px 12px;
  background-color: #fff;
  border-radius: 4px;

  .option-label-expand {
    width: 30px;
    color: #606266;
  }

  .option-text {
    flex: 1;
    margin: 0 12px;
  }

  .correct-tag {
    padding: 2px 8px;
    background-color: #f0f9eb;
    color: #67c23a;
    border-radius: 4px;
    font-size: 12px;
  }
}

.radio-group-type {
  :deep(.el-radio) {
    margin-right: 15px;
    margin-bottom: 10px;
  }
}

.drawer-form {
  padding: 20px;
}

:deep(.el-drawer__body) {
  overflow: scroll !important;
}
</style>
